package com.orange.common.base

import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import androidx.fragment.app.Fragment
import androidx.lifecycle.lifecycleScope
import com.blankj.utilcode.util.KeyboardUtils
import com.lxj.xpopup.core.BasePopupView
import com.orange.common.BR
import com.orange.common.ktx.intentOf
import com.orange.common.popup.LoadingPopup
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch

/**
 * Created by Orange on 2022/11/12 22:32.
 */
abstract class BaseFragment<DB : ViewDataBinding> : Fragment() {

    protected lateinit var binding: DB

    protected abstract val viewModel: BaseViewModel?

    /**
     * 是否首次加载
     */
    private var firstLoad: Boolean = true

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        binding = DataBindingUtil.inflate(inflater, getLayoutId(), container, false)
        binding.run {
            //默认绑定 lifecycleOwner 和 viewModel
            lifecycleOwner = viewLifecycleOwner
            setVariable(BR.vm, viewModel)
            executePendingBindings()

            //点击外部隐藏软键盘
            root.setOnClickListener {
                KeyboardUtils.hideSoftInput(it)
            }
        }
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        initView()
        initData()
    }

    override fun onResume() {
        super.onResume()
        onResumeFirst(firstLoad)
        firstLoad = false
    }

    /**
     * 获取布局 ID
     */
    protected abstract fun getLayoutId(): Int

    /**
     * 初始化控件
     */
    protected abstract fun initView()


    /**
     * 初始化数据
     */
    protected abstract fun initData()

    /**
     * Fragment 可见回调
     *
     * @param first 是否首次调用
     */
    protected open fun onResumeFirst(first: Boolean) {}

    /**
     * 自动显示加载框
     */
    fun loadingLaunch(
        popup: BasePopupView = LoadingPopup(requireActivity()),
        dispatcher: CoroutineDispatcher = Dispatchers.Main,
        block: suspend CoroutineScope.() -> Unit
    ) {
        lifecycleScope.launch(dispatcher) {
            popup.show()
            block()
        }.invokeOnCompletion {
            popup.dismiss()
        }
    }

    override fun onDestroyView() {
        super.onDestroyView()
        binding.unbind()
    }

    /**
     * 简化startActivityForResult
     * 父activity 必须是 BaseActivity
     */
    inline fun <reified T : Activity> startActivityForResult(
        vararg params: Pair<String, Any?>,
        noinline block: ((resultCode: Int, data: Intent?) -> Unit)? = null
    ) {
        val callback = block?.let {
            object : BaseActivity.OnActivityCallback {
                override fun onActivityResult(resultCode: Int, data: Intent?) {
                    block(resultCode, data)
                }
            }
        }
        (activity as BaseActivity<*>).startActivityForResult(intentOf<T>(*params), null, callback)
    }
}